package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    UserService userService;
    //获取当前登录（认证）用户的用户名
    @RequestMapping("/getLoginUsername")
    public Result getLoginUsername(){
        try{
            org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            String password = user.getPassword();
            Collection<GrantedAuthority> authorities = user.getAuthorities();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }catch (Exception e){
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }
    
    @RequestMapping("/findAll")
    public Result findAll(){

        List<User> UserList= userService.findAll();
        return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,UserList);
    }
    @RequestMapping("/findByUserId")
    public Result findByUserId(int id){

        List<User> UserList= userService.findByUserId(id);
        return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,UserList);
    }
    @RequestMapping("/update")
    public Result update(@RequestBody User User, int[] roleids){

        userService.update(User,roleids);
        return new Result(true, MessageConstant.GET_USERNAME_SUCCESS);
    }
    @RequestMapping("/add")
    public Result add(@RequestBody User User,int[] roleids){

        userService.add(User, roleids);
        return new Result(true, MessageConstant.GET_USERNAME_SUCCESS);
    }
    @RequestMapping("/delete")
    public Result delete(int id){

        userService.delete(id);
        return new Result(true, MessageConstant.GET_USERNAME_SUCCESS);
    }
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = userService.findPage(queryPageBean);
        return pageResult;
    }
}
